<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="800px"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm">
      <template #partner="{ model, field }">
        <AutoComplete
          v-model:value="model[field]"
          :dataSource="partnerDataSource"
          :filterOption="true"
        />
      </template>
    </BasicForm>
  </BasicDrawer>
</template>
<script lang="ts" setup>
  import { ref, computed, unref } from 'vue';
  import { AutoComplete } from 'ant-design-vue';
  import { BasicForm, useForm } from '@/components/Form';
  import { formSchema } from './data';
  import { BasicDrawer, useDrawerInner } from '@/components/Drawer';

  import { getPartnerList } from '@/api/partner'
  import { GetPartnerListParams } from '@/api/model/partner';
  import { partnerTypeEnum } from '@/enums/partner'
  import { createConnection, updateConnection } from '@/api/connection'

  const emit = defineEmits(['success', 'register']);
  const isUpdate = ref(true);
  const id = ref();
  const partnerDataSource = ref([]);

  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 90,
    baseColProps: { span: 24 },
    schemas: formSchema,
    showActionButtonGroup: false,
  });

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    isUpdate.value = data?.isUpdate;
    id.value = data?.record?.id;
    resetFields();
    setDrawerProps({ confirmLoading: false });
    if (unref(isUpdate)) {
      setFieldsValue({
        ...data.record,
      });
    }
    const params: GetPartnerListParams = {
      type: 'org',
    };
    const partnerResult = await getPartnerList(params);
    const partnerItems = partnerResult.items;
    const items = [];
    for (const item of partnerItems) {
      items.push({
        value: item.name,
        text: item.name,
      })
    }
    partnerDataSource.value = items;
  });

  const getTitle = computed(() => (!unref(isUpdate) ? '新增互联' : '编辑互联'));

  async function handleSubmit() {
    try {
      const values = await validate();
      [values.start_time, values.end_time] = values.time;
      values.type = partnerTypeEnum.ORG;
      delete values.time;
      setDrawerProps({ confirmLoading: true });

      if (unref(isUpdate)) {
        await updateConnection(id.value, values);
      } else {
        await createConnection(values);
      }

      closeDrawer();
      emit('success');
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>